//
//  TimeTrackerTableViewController.m
//  TimeTracker
//
//  Created by Michael Flakus on 1/6/13.
//  Copyright (c) 2013 Michael Flakus. All rights reserved.
//

#import "TaskLogTableViewController.h"
#import "TaskLogTableViewCell.h"
#import "TaskDetailViewController.h"
#import <QuartzCore/QuartzCore.h>

@interface TimeTrackerTableViewController ()

@end

@implementation TimeTrackerTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSLog(@"view did load...");
    if(_selectedDate == nil)
    {
        NSCalendar *cal = [NSCalendar currentCalendar];
        NSDateComponents *components = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];
        _selectedDate = [cal dateFromComponents:components];
        _nextDayButton.enabled = NO;
    }
    
    //[self updateTimeRepeat];
}

- (void)viewWillDisappear:(BOOL)animated
{
    // stop updating every second
    _loop = NO;
}


-(void)viewWillAppear:(BOOL)animated
{
    NSLog(@"view will appear");
    _loop = YES;
    [self updateTime];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _tasklogIds.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"TaskLogTableViewCell";
    
    TaskLogTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    // Configure the cell...
    
    int row = [indexPath row];
    cell.taskName.text = _tasklogActivityNames[row];
    cell.taskCategoryName.text = _tasklogCategoryNames[row];
    cell.taskTime.text = _tasklogTimes[row];
    
    NSDateFormatter *dateFormatterDB = [[NSDateFormatter alloc] init];
    [dateFormatterDB setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDateFormatter *dateFormatterPrint = [[NSDateFormatter alloc] init];
    [dateFormatterPrint setDateFormat:@"h:mma"];
    
    NSDate *start_time = [dateFormatterDB dateFromString:_tasklogStartTimes[row]];
    NSDate *end_time = [dateFormatterDB dateFromString:_tasklogEndTimes[row]];

    if([_tasklogEndTimes[row] isEqualToString:@""])
        cell.taskTimeRange.text = [[NSString stringWithFormat:@"%@-             ",[dateFormatterPrint stringFromDate:start_time]] lowercaseString];
    else
        cell.taskTimeRange.text = [[NSString stringWithFormat:@"%@-%@",[dateFormatterPrint stringFromDate:start_time],[dateFormatterPrint stringFromDate:end_time]] lowercaseString];
    
    return cell;
}



- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	// create the parent view that will hold header Label
	UIView* customView = [[UIView alloc] initWithFrame:CGRectMake(10.0, 0.0, 300.0, 44.0)];
    
    // create a border around the day selector header
    customView.layer.borderColor = [UIColor lightGrayColor].CGColor;
    customView.layer.borderWidth = 3.0f;
    customView.layer.backgroundColor = [UIColor lightGrayColor].CGColor;
    
    // create previous day arrow button
    _prevDayButton = [[UIButton alloc] initWithFrame:CGRectZero];
    _prevDayButton.frame = CGRectMake(10.0, 4.0, 36.0, 36.0);
    [_prevDayButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _prevDayButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13.0];
    UIImage *leftArrowBackground = [UIImage imageNamed:@"LeftArrow.png"];
    [_prevDayButton setBackgroundImage:leftArrowBackground forState:UIControlStateNormal];
    [_prevDayButton addTarget: self action: @selector(previousDayClicked:) forControlEvents: UIControlEventTouchDown];
    [customView addSubview:_prevDayButton];
    
    
    // create next day arrow button
    _nextDayButton = [[UIButton alloc] initWithFrame:CGRectZero];
    _nextDayButton.frame = CGRectMake(274.0, 4.0, 36.0, 36.0);
    [_nextDayButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _nextDayButton.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:13.0];
    UIImage *rightArrowBackground = [UIImage imageNamed:@"RightArrow.png"];
    [_nextDayButton setBackgroundImage:rightArrowBackground forState:UIControlStateNormal];
    [_nextDayButton addTarget: self action: @selector(nextDayClicked:) forControlEvents: UIControlEventTouchDown];
    _nextDayButton.enabled = NO;
    [customView addSubview:_nextDayButton];
    

	// create the date screen title as button
    _selectedDateButton = [[UIButton alloc] initWithFrame:CGRectZero];
    _selectedDateButton.frame = CGRectMake(70.0, 0.0, 180.0, 44.0);
    //_selectedDateButton.textAlignment = UITextAlignmentCenter;
    _selectedDateButton.backgroundColor = [UIColor lightGrayColor];
    _selectedDateButton.layer.borderColor = [[UIColor blackColor] CGColor];
    _selectedDateButton.layer.borderWidth = 1.0;
    [_selectedDateButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_selectedDateButton addTarget: self action: @selector(dateClicked:) forControlEvents: UIControlEventTouchDown];

    
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];
    NSDate *today = [cal dateFromComponents:components];
    
    if([today isEqualToDate:_selectedDate]) {
        [_selectedDateButton setTitle:@"TODAY" forState:UIControlStateNormal];
        _nextDayButton.enabled = NO;
    } else {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"EEE, MMM dd, yyyy"];
        [_selectedDateButton setTitle:[dateFormatter stringFromDate:_selectedDate] forState:UIControlStateNormal];
        
        // if the previous button has been pressed, then there is at least one date to move forward to
        _nextDayButton.enabled = YES;
    }
    
	[customView addSubview:_selectedDateButton];

    
	return customView;
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 44.0;
}



/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}


// sending data to detail view
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([[segue identifier] isEqualToString:@"ShowTaskEntryDetails"])
    {
        TaskDetailViewController *detailViewController = [segue destinationViewController];
                                                                     
        NSIndexPath *myIndexPath = [self.tableView indexPathForSelectedRow];
                                                                     
        int row = [myIndexPath row];
        
        detailViewController.taskDetailModel = @[_tasklogIds[row],_tasklogActivityNames[row],_tasklogCategoryNames[row],_tasklogStartTimes[row],_tasklogEndTimes[row],_tasklogNotes[row]];
    }
}



- (void) previousDayClicked: (id)sender
{
    _loop = NO;
    NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    dayComponent.day = -1;
    
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    _selectedDate = [theCalendar dateByAddingComponents:dayComponent toDate:_selectedDate options:0];
    
    [self updateTime];
}

- (void) nextDayClicked: (id)sender
{
    NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    dayComponent.day = 1;
    
    NSCalendar *theCalendar = [NSCalendar currentCalendar];
    _selectedDate = [theCalendar dateByAddingComponents:dayComponent toDate:_selectedDate options:0];
    
    _loop = YES;
    
    [self updateTime];
}

- (void) dateClicked: (id)sender
{
    NSCalendar *cal = [NSCalendar currentCalendar];
    NSDateComponents *components = [cal components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:[NSDate date]];
    _selectedDate = [cal dateFromComponents:components];
    _nextDayButton.enabled = NO;
    
    _loop = YES;
    
    [self updateTime];
}


- (void)updateTimeRepeat
{
    NSLog(@"update time repeat...");
    if(self.editing)
    {
        NSLog(@"editing mode... don't refresh...");
    }
    else
    {
        if(_loop)
        {
            [self updateTime];
            
            
            // call updateTime again after 1 second
            [self performSelector:@selector(updateTimeRepeat) withObject:self afterDelay: 1.0];
        }
    }
}

// refresh data
- (void)updateTime
{
    NSLog(@"update time...");
    
    BOOL activeTasks = NO;
    
    // load data from database
    _tasklogIds = [[NSMutableArray alloc] init];
    _tasklogActivityIds = [[NSMutableArray alloc] init];
    _tasklogActivityNames = [[NSMutableArray alloc] init];
    _tasklogCategoryNames = [[NSMutableArray alloc] init];
    _tasklogStartTimes = [[NSMutableArray alloc] init];
    _tasklogEndTimes = [[NSMutableArray alloc] init];
    _tasklogNotes = [[NSMutableArray alloc] init];
    _tasklogTimes = [[NSMutableArray alloc] init];

    
    // database lookups
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists... if it doesn't, create it and load the tables
        if ([filemgr fileExistsAtPath: _databasePath ] == NO)
        {
            const char *dbpath = [_databasePath UTF8String];
            if (sqlite3_open(dbpath, &_database) == SQLITE_OK)
            {
                char *errMsg;
                
                
                // Create activies table
                const char *createActivitiesTable = "CREATE TABLE if not exists \"activities\" (\"id\" INTEGER PRIMARY KEY  NOT NULL ,\"category_id\" INTEGER,\"activity_name\" TEXT,\"active\" CHAR DEFAULT (1) )";
                if (sqlite3_exec(_database, createActivitiesTable, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to create activities table: %s",errMsg);

                
                // Create tasklog table
                const char *createTaskLogTable = "CREATE TABLE if not exists \"tasklog\" (\"id\" INTEGER PRIMARY KEY  NOT NULL ,\"activity_id\" INTEGER,\"start_time\" DATETIME,\"end_time\" DATETIME,\"notes\" TEXT,\"active\" CHAR DEFAULT (1) )";
                if (sqlite3_exec(_database, createTaskLogTable, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to create tasklog table: %s",errMsg);

                
                // Create categories table
                const char *createCategoriesTable = "CREATE TABLE if not exists \"categories\" (\"id\" INTEGER PRIMARY KEY  NOT NULL , \"name\" VARCHAR NOT NULL , \"active\" CHAR NOT NULL  DEFAULT 1)";
                if (sqlite3_exec(_database, createCategoriesTable, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to create categories table: %s",errMsg);


                /*
                // truncate tasklog table
                const char *aaa = "delete from tasklog where 1";
                if (sqlite3_exec(_database, aaa, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to create categories table: %s",errMsg);
                */
                

                
                // SEED TABLES WITH SOME DATA
                
                /*
                 
                // seed with some activities
                const char *insertActivity1 = "INSERT INTO activities VALUES(1,2,'HCI Class','1')";
                if (sqlite3_exec(_database, insertActivity1, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert activity: %s",errMsg);
                
                const char *insertActivity2 = "INSERT INTO activities VALUES(2,1,'Racquetball at the Gym','1')";
                if (sqlite3_exec(_database, insertActivity2, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert activity: %s",errMsg);
                
                const char *insertActivity3 = "INSERT INTO activities VALUES(3,3,'Lead Web Developer (PSU)','1')";
                if (sqlite3_exec(_database, insertActivity3, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert activity: %s",errMsg);
                
                const char *insertActivity4 = "INSERT INTO activities VALUES(4,3,'IT Consulting for OLA','1')";
                if (sqlite3_exec(_database, insertActivity4, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert activity: %s",errMsg);
                
                const char *insertActivity5 = "INSERT INTO activities VALUES(5,5,'Lunch with Matt','1')";
                if (sqlite3_exec(_database, insertActivity5, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert activity: %s",errMsg);
                
                const char *insertActivity6 = "INSERT INTO activities VALUES(6,4,'Commute to WCC','1')";
                if (sqlite3_exec(_database, insertActivity6, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert activity: %s",errMsg);
                
                const char *insertActivity7 = "INSERT INTO activities VALUES(7,4,'Commute to PSU','1')";
                if (sqlite3_exec(_database, insertActivity7, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert activity: %s",errMsg);
                */
                
                
                /*
                // seed with some tasklog entries
                const char *insertTaskLog1 = "INSERT INTO \"tasklog\" VALUES(1,3,'2013-02-02 12:00:00','2013-02-02 13:00:00','This was a fun activity!','1')";
                if (sqlite3_exec(_database, insertTaskLog1, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert task: %s",errMsg);
                */
                
                
                
                /*
                NSLog(@"creating preloaded categories");
                
                 // seed with some category entries
                const char *insertCategory1 = "INSERT INTO \"categories\" VALUES(1,'Health and Wellness','1')";
                if (sqlite3_exec(_database, insertCategory1, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert category: %s",errMsg);
                
                const char *insertCategory2 = "INSERT INTO \"categories\" VALUES(2,'School','1')";
                if (sqlite3_exec(_database, insertCategory2, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert category: %s",errMsg);
                
                const char *insertCategory3 = "INSERT INTO \"categories\" VALUES(3,'Work','1')";
                if (sqlite3_exec(_database, insertCategory3, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert category: %s",errMsg);
                
                const char *insertCategory4 = "INSERT INTO \"categories\" VALUES(4,'Commuting','1')";
                if (sqlite3_exec(_database, insertCategory4, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert category: %s",errMsg);
                
                const char *insertCategory5 = "INSERT INTO \"categories\" VALUES(5,'Social','1')";
                if (sqlite3_exec(_database, insertCategory5, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert category: %s",errMsg);
                
                */
                
                
                
                /*
                const char *insertPosition = "INSERT INTO positions VALUES(1,'PSU','Web Developer',240,'day','1')";
                if (sqlite3_exec(_database, insertPosition, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert position: %s",errMsg);
                
                
                const char *insertClient1 = "INSERT INTO clients VALUES(1,'CARS',70,'hour','1')";
                if (sqlite3_exec(_database, insertClient1, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert client: %s",errMsg);
                
                const char *insertClient2 = "INSERT INTO clients VALUES(2,'Inogen',70,'hour','1')";
                if (sqlite3_exec(_database, insertClient2, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert client: %s",errMsg);
                
                const char *insertClient3 = "INSERT INTO clients VALUES(3,'Oregon Library Association',90,'hour','1')";
                if (sqlite3_exec(_database, insertClient3, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert client: %s",errMsg);
 
                
                const char *insertProject1 = "INSERT INTO projects VALUES(1,1,'CPI','1')";
                if (sqlite3_exec(_database, insertProject1, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert project: %s",errMsg);
                
                const char *insertProject2 = "INSERT INTO projects VALUES(2,2,'General','1')";
                if (sqlite3_exec(_database, insertProject2, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert project: %s",errMsg);
                
                const char *insertProject3 = "INSERT INTO projects VALUES(3,3,'Oregon Authors Updates','1')";
                if (sqlite3_exec(_database, insertProject3, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert project: %s",errMsg);

                
                const char *insertTimesheet = "INSERT INTO timesheet VALUES(2,1,1,'2013-01-11 18:00:00',NULL,'1')";
                if (sqlite3_exec(_database, insertTimesheet, NULL, NULL, &errMsg) != SQLITE_OK)
                    NSLog(@"Failed to insert timesheet entry: %s",errMsg);
                */
                
                sqlite3_close(_database);
                
            } else {
                NSLog(@"Failed to open/create database");
            }
        }
        else {
            //NSLog(@"Database exists");
        }
        
        
        
        // open database
        if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
        {
            NSLog(@"An error has occured when trying to open the database");
        }
        
        // lookup tasklog entries for selected date
        
        NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
        dayComponent.day = 1;
        
        NSCalendar *theCalendar = [NSCalendar currentCalendar];
        NSDate *nextDay = [theCalendar dateByAddingComponents:dayComponent toDate:_selectedDate options:0];
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        
        
        NSString *select_tasklogEntries = [NSString stringWithFormat:@"SELECT tasklog.id,activity_id,activities.activity_name,categories.name as category_name,start_time,end_time,notes from tasklog,activities,categories where start_time >= '%@' and start_time < '%@' and activities.id = tasklog.activity_id and categories.id = activities.category_id and tasklog.active = 1",[dateFormatter stringFromDate:_selectedDate],[dateFormatter stringFromDate:nextDay]];
        
        //NSLog(@"query: %@",select_tasklogEntries);
        
        const char *select_tasklogEntries_const = [select_tasklogEntries UTF8String];
        
        sqlite3_stmt *res_tasklogEntries;
        if(sqlite3_prepare(_database, select_tasklogEntries_const, -1, &res_tasklogEntries, NULL) != SQLITE_OK)
        {
            NSLog(@"Problem with prepare statement: %s",select_tasklogEntries_const);
            NSLog(@"%s Prepare failure '%s' (%1d)", __FUNCTION__, sqlite3_errmsg(_database), sqlite3_errcode(_database));
        }
        else
        {
            while (sqlite3_step(res_tasklogEntries)==SQLITE_ROW) {
                
                //NSLog(@"Found a tasklog entry");
                
                [_tasklogIds addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,0)]];
                [_tasklogActivityIds addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,1)]];
                [_tasklogActivityNames addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,2)]];
                [_tasklogCategoryNames addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,3)]];
                [_tasklogStartTimes addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,4)]];
                
                             
                // convert DateTime NSStrings to NSDates
                NSDateFormatter *df = [[NSDateFormatter alloc] init];
                [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSDate *start_time = [df dateFromString: [NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,4)]];
                NSDate *end_time;
                
                if(sqlite3_column_text(res_tasklogEntries,5) != NULL)
                {
                    [_tasklogEndTimes addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,5)]];
                    end_time = [df dateFromString: [NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,5)]];
                } else {
                    [_tasklogEndTimes addObject:@""];
                    end_time = [NSDate date];
                    
                    // there is at least one active task for this date
                    activeTasks = YES;
                    NSLog(@"active task: %@",[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,2)]);
                }
                // set time for task (h:mm)
                
                
                
                NSTimeInterval secondsTracked = [end_time timeIntervalSinceDate: start_time];
                //NSLog(@"seconds tracked for task: %f",secondsTracked);
                
                int hours = 0;
                int minutes = 0;
                int seconds = 0;
                
                hours = secondsTracked / 3600;
                minutes = (secondsTracked - (hours * 3600)) / 60;
                seconds = (secondsTracked - (hours * 3600) - (minutes * 60));
                
                NSString *minutes_str = @"";
                // pad to two digits
                if(minutes < 10)
                    minutes_str = [NSString stringWithFormat:@"0%d",minutes];
                else
                    minutes_str = [NSString stringWithFormat:@"%d",minutes];
                
                NSString *seconds_str = @"";
                // pad to two digits
                if(seconds < 10)
                    seconds_str = [NSString stringWithFormat:@"0%d",seconds];
                else
                    seconds_str = [NSString stringWithFormat:@"%d",seconds];
                
                NSString *trackedTime = [NSString stringWithFormat:@"%d:%@:%@",hours,minutes_str,seconds_str];
                
                [_tasklogTimes addObject:trackedTime];
                
                [_tasklogNotes addObject:[NSString stringWithUTF8String:(char *) sqlite3_column_text(res_tasklogEntries,6)]];
                
            }
            // release db data
            sqlite3_finalize(res_tasklogEntries);
        }
    }
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
    
    if(activeTasks && _loop && !self.editing)
    {
        //_loop = YES;
        [self performSelector:@selector(updateTime) withObject:self afterDelay: 1.0];

    }
    else
    {
        _loop = NO;
    }
    
    if(!self.editing)
    {
        [self.tableView reloadData];
    }
}

- (IBAction)newActivityButtonPressed:(id)sender {
    //NSLog(@"new activity button pressed");
    self.tabBarController.selectedIndex = 1;
}




// functions for deleting
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"row selected to be deleted: %d",[indexPath row]);
    
    @try {
        
        // connect to db
        
        NSString *docsDir;
        NSArray *dirPaths;
        
        // Get the documents directory
        dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        
        docsDir = dirPaths[0];
        
        // Build the path to the database file
        _databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"TimeTracker.sqlite"]];
        
        NSFileManager *filemgr = [NSFileManager defaultManager];
        
        // check to see if database already exists...
        if ([filemgr fileExistsAtPath: _databasePath ] == YES)
        {
            // open database
            if(!(sqlite3_open([_databasePath UTF8String], &_database) == SQLITE_OK))
            {
                NSLog(@"An error has occured when trying to open the database");
            }
            
            char *errMsg;
            
            // TODO: check to make sure category is not assigned to activities
            // possible solutions: display alert to user OR assign activities to special "Uncategorized" category that cannot be deleted
            
            
            // delete activity
            NSString *delete_sql = [NSString stringWithFormat:@"update tasklog set active = 0 where id = '%@'",_tasklogIds[[indexPath row]]];
            NSLog(@"delete query: %@",delete_sql);
            const char *delete_sql_const = [delete_sql UTF8String];
            if (sqlite3_exec(_database, delete_sql_const, NULL, NULL, &errMsg) != SQLITE_OK)
                NSLog(@"Failed: %s",errMsg);
        }
        else
        {
            NSLog(@"Error: database could not be found in ActivitiesViewController");
        }
    }
    @catch (NSException *exception) {
        NSLog(@"An exception occured: %@", [exception reason]);
    }
    @finally {
        // close the database connection
        sqlite3_close(_database);
    }
    //self.editing = NO;
    //[self updateTime];
}

- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
    //NSLog(@"editing is done... reload the table");
    self.editing = NO;
    _loop = YES;
    [self updateTime];
}


- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath {
	// Do not indent rows when in editing mode.
	return NO;
}






@end
